<?php

namespace app\common\exception;

use think\db\exception\DataNotFoundException;
use think\db\exception\ModelNotFoundException;
use think\exception\Handle;
use think\exception\HttpException;
use think\exception\HttpResponseException;
use think\exception\ValidateException;
use think\Response;
use think\response\Json;
use Throwable;

/**
 * 应用异常处理类
 */
class ExceptionHandle extends Handle
{

    // 状态码
    private $status;

    // 错误信息
    private $msg;

    // 输出的数据
    private $data = [];

    // 扩展参数
    private $extra = [];

    /**
     * 不需要记录信息（日志）的异常类列表
     * @var array
     */
    protected $ignoreReport = [
        HttpException::class,
        HttpResponseException::class,
        ModelNotFoundException::class,
        DataNotFoundException::class,
        ValidateException::class,
    ];

    /**
     * 记录异常信息（包括日志或者其它方式记录）
     *
     * @access public
     * @param Throwable $exception
     * @return void
     */
    public function report(Throwable $exception): void
    {
        // 使用内置的方式记录异常日志
        if (!($exception instanceof BaseException)) {
            parent::report($exception);
        }
    }

    /**
     * Render an exception into an HTTP response.
     *
     * @access public
     * @param \think\Request $request
     * @param Throwable $e
     * @return Response
     */
    public function render($request, Throwable $e): Response
    {
        if ($e instanceof HttpResponseException) {
            return $e->getResponse();
        }

        // 自定义异常
        if ($e instanceof BaseException) {
            $this->status = $e->status;
            $this->msg = $e->msg;
            $this->data = $e->data;
            $extend = property_exists($e, 'extend') ? $e->extend : [];
            return $this->renderJson($extend);
        }

        // 系统运行的异常
        $this->status = config('status.error');
        $this->msg = $e->getMessage() ?: '很抱歉，服务器内部错误';

        // 如果是debug模式, 输出调试信息
        if (env('APP_DEBUG')) {
            // return parent::render($request, $e);
            $this->setDebugData($e);
        }

        return $this->renderJson($this->extra);
    }

    /**
     * @notes 返回json格式
     * @param array $extend
     * @return Json
     * @author mjf
     * @date 2022/4/13 17:02
     */
    private function renderJson(array $extend = []): Json
    {
        $data = [
            'status' => $this->status,
            'msg' => $this->msg,
            'data' => $this->data
        ];
        return json(array_merge($data, $extend));
    }

    /**
     * @notes 设置debug数据
     * @param Throwable $e
     * @author mjf
     * @date 2022/4/13 17:404
     */
    private function setDebugData(Throwable $e): void
    {
        $this->extra['debug'] = [
            'name' => get_class($e),
            'file' => $e->getFile(),
            'line' => $e->getLine(),
            'code' => $this->getCode($e),
            'message' => $this->getMessage($e),
            'trace' => $e->getTrace(),
            'source' => $this->getSourceCode($e),
        ];
    }

}
